<?php

ini_set("memory_limit", "100M");
ini_set("max_execution_time", 36000);

require_once('../../config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/PHT.php');
require_once(SITE_ROOT . 'class/bean/Country.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');
require_once(SITE_ROOT . 'class/bean/League.class.php');
require_once(SITE_ROOT . 'class/db/DBDivision.class.php');
require_once(SITE_ROOT . 'class/db/DBLeague.class.php');

try {
	$HT = new CHPPConnection(VERSION, CHPPID, CHPPKEY, SITE_ROOT . 'tmp/hattrick/');
	if ($HT->connectUser(HTUSER, HTSECCODE)) {
		for ($i=1; $i<=248024; $i+=100) {
			try {
				if ($HT instanceof CHPPConnection) {
					storeLeagues($i, $i+100, $HT);
					$HT->clearLeagues();
					sleep(1);
				}
				else break 1;
			}
			catch (Exception $e) {}
		}
		$HT->disconnect();
	}
	else echo "Login error !";
}
catch (Exception $e) {
	echo $e->getMessage();
	$HT->disconnect();
}

function storeLeagues($start, $end, $HT) {
		$leagues = new ArrayObject();
		$divisions = new ArrayObject();
		for ($i=$start; $i<=$end; $i++) {
			try {
				$country = new Country();
				$country->setCountryID($HT->getLeague($i)->getLeagueId());
				$division = new Division();
				$division->setCountry($country);
				$division->setDivisionID($HT->getLeague($i)->getLeagueLevel());
				$divisions->append($division);
				$league = new League();
				$league->setDivision($division);
				$league->setLeagueID($HT->getLeague($i)->getLeagueLevelId());
				$league->setName($HT->getLeague($i)->getLeagueLevelName());
				$leagues->append($league);
			}
			catch (Exception $e) {}
		}
		$dbdivision = new DBDivision();
		$dbdivision->saveDivisions($divisions);
		$dbleague = new DBLeague();
		$dbleague->saveLeagues($leagues);
		unset($leagues, $divisions, $dbleague, $dbdivision);
	}

?>